package com.malty.mall.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malty.mall.dao.ums.UmsRoleMapper;
import com.malty.mall.domain.dto.req.UmsRoleParam;
import com.malty.mall.domain.entity.ums.UmsAdminRoleRelation;
import com.malty.mall.domain.entity.ums.UmsRole;
import com.malty.mall.service.ums.IUmsAdminRoleService;
import com.malty.mall.service.ums.IUmsRoleService;
import com.malty.mall.util.PreconditionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author malty
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UmsRoleServiceImpl extends ServiceImpl<UmsRoleMapper, UmsRole> implements IUmsRoleService {
    private IUmsAdminRoleService adminRoleService;

    @Autowired
    public void setAdminRoleService(IUmsAdminRoleService adminRoleService) {
        this.adminRoleService = adminRoleService;
    }

    @Override
    public Boolean create(UmsRoleParam umsRoleParam) {
        UmsRole umsRole = new UmsRole(umsRoleParam);
        List<UmsRole> list = this.list(Wrappers.<UmsRole>lambdaQuery().eq(UmsRole::getRoleName, umsRoleParam.getRoleName()));
        PreconditionUtils.check(!ObjectUtils.isEmpty(list), "角色已经存在");
        boolean save = this.save(umsRole);
        PreconditionUtils.check(!save, "创建失败");
        return true;
    }

    @Override
    public List<UmsRoleParam> listByUid(Integer uid) {
        List<UmsAdminRoleRelation> relations = adminRoleService.list(Wrappers.<UmsAdminRoleRelation>lambdaQuery().eq(UmsAdminRoleRelation::getAdminId, uid));
        List<Integer> roleIds = relations.stream().map(UmsAdminRoleRelation::getRoleId).collect(Collectors.toList());
        List<UmsRole> umsRoles = new ArrayList<>();
        if (!ObjectUtils.isEmpty(roleIds)) {
            umsRoles = this.list(Wrappers.<UmsRole>lambdaQuery().in(UmsRole::getId, roleIds));
        }
        return UmsRole.getParamBatch(umsRoles);
    }

    @Override
    public List<UmsRoleParam> listAll() {
        List<UmsRole> roles = this.list();
        return UmsRole.getParamBatch(roles);
    }
}
